<template>
  <el-dialog v-model="dialogVisible" title="新建用户" width="400px">
    <el-form :model="newUserForm">
      <el-form-item label="姓名">
        <el-input v-model="newUserForm.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input type="number" v-model="newUserForm.age"></el-input>
      </el-form-item>
      <el-form-item label="邮件">
        <el-input v-model="newUserForm.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="newUser">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import { createUser } from '@/alova/api';

const dialogVisible = ref(false);
const newUserForm = ref({ name: '', age: '', email: '' });
const emit = defineEmits(['userCreated']);

const newUser = async () => {
  try {
    await createUser(newUserForm.value);
    dialogVisible.value = false;
    emit('userCreated'); // 触发事件通知父组件
  } catch (error) {
    console.error('创建失败', error);
  }
};

const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });// 显式暴露子组件，使父组件可以通过 ref 访问并调用 openDialog 方法
</script>

<style>
.error {
  color: red;
}
</style>